﻿using System.Collections;
using System.Collections.Generic;
using TcpSocket;
using UnityEngine;

public class SocketClientManager : MonoBehaviour
{
    public static string IP = "127.0.0.1";
    public static int Port = 10010;

    static TcpSocketClient socketClient;
    static bool isConnected = false;

    private void Start()
    {
        socketClient = new TcpSocketClient(IP, Port);
        socketClient.Initialized();
        socketClient.OnReceive += OnReceive;
        socketClient.OnConnected += OnConnected;
        socketClient.OnError += OnError;
        socketClient.OnDisconnected += OnDisconnected;
        socketClient.OnConnInterval += OnConnInterval;
        socketClient.Connected(100);
    }

    private void Update()
    {
        socketClient.ConnectedInterval();
    }
    /// <summary>
    /// 连接成功;
    /// </summary>
    void OnConnected()
    {
        Debug.Log("连接成功!+");
        isConnected = true;
    }

    void OnConnInterval(int count)
    {
        Debug.Log("正在尝试第 "+count + " 次连接!");
    }

    /// <summary>
    /// 读取消息
    /// </summary>
    /// <param name="msg"></param>
    void OnReceive(string msg)
    {
        Debug.Log("收到消息: "+msg);
        GameManager.Instence.SetText(msg);
    }

    /// <summary>
    /// 连接错误
    /// </summary>
    void OnError()
    {
        Debug.Log("连接失败!+");
        isConnected = false;
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    void OnDisconnected()
    {
        Debug.Log("断开连接!+");
        isConnected = false;
    }

    public static bool OnSendToServer(string msg)
    {
        if (isConnected)
        {
            socketClient.Send(msg);
        }
        return isConnected;
    }

    void _destroy()
    {
        if (socketClient != null) socketClient.Close();
    }

    private void OnDestroy()
    {
        _destroy();
    }

    private void OnApplicationQuit()
    {
        _destroy();
    }
}
